import { Button, Checkbox, Form, Input, Space } from 'antd';
import { useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';

type FieldType = {
  username: string;
  password: string;
  remember?: boolean;
};

function PageEntry() {
  const [form] = Form.useForm<FieldType>();
  const nav = useNavigate();

  useEffect(() => {
    const { username, password } = getRememberStore();
    form.setFieldsValue({
      username,
      password,
      remember: !!username && !!password,
    });
  }, []);

  function onFinish(values: FieldType) {
    if(values.remember) {
      setRememberStore(values.username, values.password);
    }else {
      removeRememberStore();
    }
    nav('/manage/list');
  };

  function setRememberStore(username: string, password: string) {
    localStorage.setItem('username', username);
    localStorage.setItem('password', password);
  }

  function getRememberStore() {
    return {
      username: localStorage.getItem('username') || '',
      password: localStorage.getItem('password') || '',
    };
  }

  function removeRememberStore() {
    localStorage.removeItem('username');  
    localStorage.removeItem('password');  
  }

  return <div className="w-500px mx-auto mt-100px">
    <Form 
      form={form}
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      onFinish={onFinish}
    >
      <Form.Item<FieldType>
        label="用户名"
        name="username"
        rules={[{ required: true, message: '请输入用户名' }]}
      >
        <Input placeholder='请输入用户名' allowClear />
      </Form.Item>

      <Form.Item<FieldType>
        label="密码"
        name="password"
        rules={[{ required: true, message: '请输入密码' }]}
      >
        <Input.Password placeholder='请输入密码' allowClear />
      </Form.Item>

      <Form.Item<FieldType> name="remember" valuePropName="checked" label={null}>
        <Checkbox>记住密码</Checkbox>
      </Form.Item>

      <Form.Item label={null}>
        <Space>
          <Button type="primary" htmlType="submit">
            登录
          </Button>
          <Link to="/register">没账号？去注册</Link>
        </Space>
      </Form.Item>
    </Form>
  </div>
}

export default PageEntry;